package com.example.servicelogin.services.impl;

import com.example.constans.Constants;
import com.example.entity.utils.StringTools;
import com.example.servicelogin.mapper.UserInfoMapper;
import com.example.login.dto.TokenUserInfoDto;
import com.example.login.po.UserEasy;
import com.example.servicelogin.services.UserInfoServie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserInfoServiceImpl implements UserInfoServie {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private RedisServiceImpl redisService;

    @Override
    public TokenUserInfoDto login(String username, String password) {
        UserEasy userEasy = userInfoMapper.queryByUserName(username);
        // 1. 校验用户名密码是否为空
        if (userEasy == null || username == null || username.isEmpty() || password == null || password.isEmpty()) {
            return null;
        }
        // 2. 校验用户名密码是否正确
        if (!username.equals(userEasy.getUserName()) || !password.equals(userEasy.getUserPassword())) {
            return null;
        }

        // 3. 校验通过，返回token
        TokenUserInfoDto tokenUserInfoDto = new TokenUserInfoDto();
        tokenUserInfoDto.setUserId(userEasy.getUserId());
        //        用userid + 20长度随机数生成 token
        String token = StringTools.encodeMD5(tokenUserInfoDto.getUserId()) + StringTools.getRandomString(20);
        tokenUserInfoDto.setToken(token);
        //将 token 存入 redis
        redisService.set(Constants.REDIS_KEY_USER_TOKEN + tokenUserInfoDto.getToken(),
                tokenUserInfoDto,Constants.TOKEN_TIME);
        return tokenUserInfoDto;
    }
}
